<template>
    <div>
        <form  class="card comment-form" @submit.prevent="onSubmit">
          <div class="card-block">
            <textarea :disabled="postLoading" v-model="comment.body" class="form-control" placeholder="Write a comment..." rows="3"></textarea>
          </div>
          <div class="card-footer">
            <img :src="user.image" class="comment-author-img" />
            <button :disabled="postLoading" class="btn btn-sm btn-primary">
             Post Comment
            </button>
          </div>
        </form>
        
        <div class="card" v-for="comment in comments" :key="comment.id">
          <div class="card-block">
            <p class="card-text">{{ comment.body }}</p>
          </div>
          <div class="card-footer">
            <nuxt-link 
                :to="{
                    name: 'profile',
                    query: {
                        username: comment.author.username
                    }
                }"
                class="comment-author">
              <img :src="comment.author.image" class="comment-author-img" />
            </nuxt-link>
            &nbsp;
            <nuxt-link :to="{
                    name: 'profile',
                    query: {
                        username: comment.author.username
                    }
                }" class="comment-author">{{ comment.author.username }}</nuxt-link>
            <span class="date-posted">{{ comment.createdAt | date('MMM DD, YYYY') }}</span>
            <span class="mod-options" v-if="comment.author.username === user.username" @click="onDelete(comment.id)">
              <i class="ion-trash-a"></i>
            </span>
          </div>
        </div>
    </div>
</template>

<script>
import { getComments, addComment, deleteComment } from '@/api/article'
import { mapState } from 'vuex'
export default {
   name: 'ArticlePost',
   props: {
     article:{
       type: Object,
       required: true
     }
     
   },
   data () {
      return {
        comments: [],
        comment: {
          body: ''
        },
        postLoading: false
      }
   },
   async mounted () {
     const { data } = await getComments(this.article.slug)
     this.comments = data.comments
   },
   computed: {
       ...mapState(['user'])
   },
   methods: {
     // 新增评论
    async onSubmit () {
      this.postLoading = true
      const { data } = await addComment(this.article.slug, { comment: this.comment })
      this.comments.unshift(data.comment)
      this.comment.body = ''
      this.postLoading = false
    },
    async onDelete (id) {
      const { data } = await deleteComment(this.article.slug, id)
      this.comments = this.comments.filter(comment => comment.id !== id )
    }
   }
};
</script>
